package middleware

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math/rand/v2"
	"os"
	"time"

	"gitee.com/saroeleven/ginrcpv2/log"
	"github.com/gin-gonic/gin"
)

const x_trace = "x_trace"

func Xtace() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		begin := time.Now()
		// generate traceId
		traceId := ctx.GetHeader(x_trace)
		if traceId == "" {
			traceId = generateTraceId()
		}
		//set request header
		ctx.Request.Header.Set(x_trace, traceId)

		//set response header
		ctx.Header(x_trace, traceId)
		ctx.Next()
		log.Infof("url:%s , 耗时:%s , traceId:%s", ctx.Request.URL.String(), time.Since(begin).String(), traceId)
	}
}

func generateTraceId() string {
	rndStr := fmt.Sprint(os.Getpid(), time.Now().UnixNano(), rand.Float64())
	hashBytes := md5.Sum([]byte(rndStr))
	return hex.EncodeToString(hashBytes[:])
}
